package com.example.qnn_app;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import org.json.JSONObject;

import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.ArrayDeque;
import java.util.Deque;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

public class MonitorActivity extends AppCompatActivity {
    private static final String TAG = "AutoCallAI";
    private static final int PERMISSION_REQUEST_CODE = 1002;

    private TextView tvTitle;
    private TextView tvQueue;
    private TextView tvStatus;
    private TextView tvLog;
    private Button btnConfig;
    private android.widget.ScrollView scrollLog;
    private final Deque<String> recentLogs = new ArrayDeque<>();
    private final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());

    private String configuredDeviceCode;
    private TelephonyManager telephonyManager;
    private PhoneStateListener phoneStateListener;
    private boolean isCallActive = false;
    private String currentSessionId;

    private Connection mqConnection;
    private Channel mqChannel;

    private final String[] permissions = new String[]{
            Manifest.permission.CALL_PHONE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monitor);

        tvTitle = findViewById(R.id.tv_title);
        tvQueue = findViewById(R.id.tv_queue);
        tvStatus = findViewById(R.id.tv_status);
        tvLog = findViewById(R.id.tv_log);
        scrollLog = findViewById(R.id.scroll_log);
        btnConfig = findViewById(R.id.btn_goto_config);

        SharedPreferences sp = getSharedPreferences("app_prefs", MODE_PRIVATE);
        configuredDeviceCode = sp.getString("device_code", null);
        if (configuredDeviceCode == null || configuredDeviceCode.trim().isEmpty()) {
            Toast.makeText(this, "请先配置设备码", Toast.LENGTH_LONG).show();
            startActivity(new Intent(this, MainActivity.class));
            finish();
            return;
        }
        configuredDeviceCode = configuredDeviceCode.trim();
        tvTitle.setText("拨号监控");
        tvQueue.setText("队列：call_task_" + configuredDeviceCode);

        btnConfig.setOnClickListener(v -> {
            Intent i = new Intent(this, MainActivity.class);
            i.putExtra("force_config", true);
            startActivity(i);
        });

        checkPermissions();
        initTelephonyManager();
        restartRabbitMqConsumer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try { if (mqChannel != null && mqChannel.isOpen()) mqChannel.close(); } catch (Exception ignored) {}
        try { if (mqConnection != null && mqConnection.isOpen()) mqConnection.close(); } catch (Exception ignored) {}
    }

    private void checkPermissions() {
        boolean allGranted = true;
        for (String p : permissions) {
            if (ContextCompat.checkSelfPermission(this, p) != PackageManager.PERMISSION_GRANTED) {
                allGranted = false; break;
            }
        }
        if (!allGranted) {
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
        }
    }

    private void initTelephonyManager() {
        telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        phoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String phoneNumber) {
                super.onCallStateChanged(state, phoneNumber);
                // 按需求不记录通话状态到日志，仅内部状态控制
                if (state == TelephonyManager.CALL_STATE_OFFHOOK && !isCallActive) {
                    isCallActive = true;
                } else if (state == TelephonyManager.CALL_STATE_IDLE && isCallActive) {
                    isCallActive = false;
                }
            }
        };
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                == PackageManager.PERMISSION_GRANTED) {
            telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }
    }

    private void restartRabbitMqConsumer() {
        try { if (mqChannel != null && mqChannel.isOpen()) mqChannel.close(); } catch (Exception ignored) {}
        try { if (mqConnection != null && mqConnection.isOpen()) mqConnection.close(); } catch (Exception ignored) {}
        startRabbitMqConsumer();
    }

    private void startRabbitMqConsumer() {
        new Thread(() -> {
            try {
                String mqHost = "192.168.1.11";
                int mqPort = 5672;
                String mqUser = "admin";
                String mqPass = "111111";

                ConnectionFactory factory = new ConnectionFactory();
                factory.setHost(mqHost);
                factory.setPort(mqPort);
                factory.setUsername(mqUser);
                factory.setPassword(mqPass);
                factory.setAutomaticRecoveryEnabled(true);

                mqConnection = factory.newConnection();
                mqChannel = mqConnection.createChannel();

                String queueName = "call_task_" + configuredDeviceCode;
                mqChannel.queueDeclare(queueName, true, false, false, null);

                DeliverCallback callback = (consumerTag, delivery) -> {
                    try {
                        String body = new String(delivery.getBody(), StandardCharsets.UTF_8);
                        Log.d(TAG, "收到MQ消息: " + body);
                        JSONObject data = new JSONObject(body);
                        String sessionId = data.optString("session_id", "mq_" + UUID.randomUUID().toString().substring(0, 8));

                        String msgDeviceId = data.optString("device_id", "").trim();
                        if (!msgDeviceId.isEmpty() && !msgDeviceId.equals(configuredDeviceCode)) {
                            // 只需要接收与拨号日志，这里不输出
                            return;
                        }

                        String phoneNumber = data.optString("phone",
                                data.optString("phone_number",
                                        data.optString("number", "")));
                        if (phoneNumber == null || phoneNumber.trim().isEmpty()) {
                            addLog("错误", "任务缺少号码");
                            return;
                        }
                        String finalPhone = phoneNumber.trim();
                        String timeStr = data.optString("time", "");
                        addLogWithExternalTime("接收", finalPhone, timeStr);
                        runOnUiThread(() -> makeCall(sessionId, finalPhone));
                    } catch (Exception e) {
                        Log.e(TAG, "处理MQ消息失败", e);
                        // 不输出到日志
                    }
                };

                mqChannel.basicConsume(queueName, true, callback, consumerTag -> {});
                runOnUiThread(() -> {
                    Toast.makeText(this, "已开始监听: " + queueName, Toast.LENGTH_LONG).show();
                    tvStatus.setText("已连接并监听");
                });
            } catch (Exception e) {
                Log.e(TAG, "连接RabbitMQ失败", e);
                runOnUiThread(() -> {
                    tvStatus.setText("连接失败");
                    Toast.makeText(this, "RabbitMQ连接失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                });
            }
        }).start();
    }

    private void makeCall(String sessionId, String phoneNumber) {
        currentSessionId = sessionId;
        sendCallStatusUpdate("dialing");
        addLog("拨号", phoneNumber);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                == PackageManager.PERMISSION_GRANTED) {
            try {
                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:" + phoneNumber));
                startActivity(callIntent);
                return;
            } catch (Exception e) {
                Log.e(TAG, "ACTION_CALL 失败，降级 ACTION_DIAL", e);
            }
        }
        try {
            Intent dialIntent = new Intent(Intent.ACTION_DIAL);
            dialIntent.setData(Uri.parse("tel:" + phoneNumber));
            startActivity(dialIntent);
        } catch (Exception e) {
            Log.e(TAG, "ACTION_DIAL 也失败", e);
            sendCallStatusUpdate("failed");
            Toast.makeText(this, "无法拨号: " + phoneNumber, Toast.LENGTH_SHORT).show();
        }
    }

    private void sendCallStatusUpdate(String status) { /* 仅上报内部状态，不写日志 */ }

    private void addLog(String tag, String message) {
        String time = timeFormat.format(new Date());
        String line = "[" + time + "] " + tag + " " + message;
        recentLogs.addLast(line);
        while (recentLogs.size() > 10) {
            recentLogs.removeFirst();
        }
        renderLogs();
    }

    private void addLogWithExternalTime(String tag, String message, String externalTime) {
        String shownTime = (externalTime == null || externalTime.isEmpty()) ? timeFormat.format(new Date()) : externalTime;
        String line = "[" + shownTime + "] " + tag + " " + message;
        recentLogs.addLast(line);
        while (recentLogs.size() > 10) {
            recentLogs.removeFirst();
        }
        renderLogs();
    }

    private void renderLogs() {
        runOnUiThread(() -> {
            StringBuilder sb = new StringBuilder();
            for (String s : recentLogs) {
                if (sb.length() > 0) sb.append('\n');
                sb.append(s);
            }
            tvLog.setText(sb.toString());
            if (scrollLog != null) scrollLog.post(() -> scrollLog.fullScroll(android.view.View.FOCUS_DOWN));
        });
    }
}


